package com.loiot.baqi.dao;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.mybatis.spring.support.SqlSessionDaoSupport;

import com.loiot.baqi.utils.DBParams;
import com.loiot.baqi.utils.VirtualORM;
import com.loiot.commons.utils.JsonUtil;


/**
 * base数据访问层。
 * 
 * @author 
 */
public class  BaseDaoV1 extends SqlSessionDaoSupport {

	
    
    public Object addV1(Object t) throws Exception{
    	DBParams dbParam=VirtualORM.save(t);
		this.getSqlSession().insert("Common.insertBySql", dbParam);
		return t;
	}
    
    public Object updateV1(Object t,String whereSql) throws Exception{
    	if(StringUtils.isBlank(whereSql)){
    		throw new NullPointerException();
    	}
    	DBParams dbParam=VirtualORM.update(t, true, whereSql);
		this.getSqlSession().insert("Common.updateBySql", dbParam);
		return t;
	}
    
    public Object updateByPkV1(Object t) throws Exception{
    	DBParams dbParam=VirtualORM.update(t, true);
		this.getSqlSession().update("Common.updateBySql", dbParam);
		return t;
	}
    
    
    public boolean deleteByPkV1(Class classsz,Long id) throws Exception{
    	DBParams dbParam=VirtualORM.deleteCacheByPk(classsz,id);
		this.getSqlSession().update("Common.deleteBySql", dbParam);
		return true;
	}
    
    public Object getSimpleObjectByIdV1(Class classsz,Long id) throws Exception{
    	DBParams dbParam=VirtualORM.getObjectById(classsz, id);
		HashMap<String,Object> map =(HashMap) this.getSqlSession().selectOne("Common.selectBySql", dbParam);
		if(map==null){
			return null;
		}
		HashMap<String,Object> newMap = new HashMap<String,Object>();
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String)entry.getKey();
			Object val = entry.getValue();
			newMap.put(VirtualORM.convertToJavaProperty(key),val);
		}
		Object obj =JsonUtil.toObject(JsonUtil.toJson(newMap), classsz);
		return  obj;
	}
    
    public Object getSimpleObjectV1(Object obj) throws Exception{
    	DBParams dbParam=VirtualORM.getObject(obj);
		HashMap<String,Object> map =(HashMap) this.getSqlSession().selectOne("Common.selectBySql", dbParam);
		if(map==null){
			return null;
		}
		HashMap<String,Object> newMap = new HashMap<String,Object>();
		Iterator iter = map.entrySet().iterator();
		while (iter.hasNext()) {
			Map.Entry entry = (Map.Entry) iter.next();
			String key = (String)entry.getKey();
			Object val = entry.getValue();
			newMap.put(VirtualORM.convertToJavaProperty(key),val);
		}
		obj =JsonUtil.toObject(JsonUtil.toJson(newMap), obj.getClass());
		return  obj;
	}

}
